<template>
    <div class="Image-loader-container">
        <img v-if="!everythingDone" class="placeholder" :src="placeholder" alt="占位图片">
        <img @load="handleLoad" :style="{ opacity: originOpacity, transition: `${duration}ms` }" :src="src" alt="原始图片">
    </div>
</template>

<script>
export default {
    props: {
        // 原始图片地址，必填
        src: {
            type: String,
            required: true,
        },
        // 原始图片加载完成前的占位地址
        placeholder: {
            type: String,
            required: true,
        },
        duration: {
            type: Number,
            default: 500,
        }
    },
    data() {
        return {
            originLoaded: false, // 原图是否加载完成
            everythingDone:false, // 是否所有事情都完成了
        };
    },
    computed: {
        originOpacity() { // 原图的透明度
            // 如果原图加载完成了，透明度是1，否则就是0
            return this.originLoaded ? 1 : 0;
        }
    },
    methods: {
        handleLoad() {
            this.originLoaded = true;
            setTimeout(() => {
                this.everythingDone = true;
                this.$emit('load');
            }, this.duration);
        }
    }
}
</script>

<style lang="less" scoped>
@import '~@/styles/mixin.less';

.Image-loader-container {
    height: 100%;
    width: 100%;
    text-align: center;
    position: relative;
    overflow: hidden;

    img {
        .self-fill();
        object-fit: cover;
    }

    .placeholder {
        transition: all 3s;
        opacity: 1;
        filter: blur(2vw);
    }
}
</style>